#include <stdio.h>

#include "bitmap.h"

int WriteBitmapFile(char* filename, pixel_t* bitmapImage, int x_size, int y_size){
	FILE *fpBMP;

	int i, j;

	// Header and 3 bytes per pixel
	unsigned long ulBitmapSize = (y_size * x_size * 3)+54;
	char ucaBitmapSize[4];

	ucaBitmapSize[3]= (ulBitmapSize & 0xFF000000) >> 24;
	ucaBitmapSize[2]= (ulBitmapSize & 0x00FF0000) >> 16;
	ucaBitmapSize[1]= (ulBitmapSize & 0x0000FF00) >> 8;
	ucaBitmapSize[0]= (ulBitmapSize & 0x000000FF);

	/* Create bitmap file */
	fpBMP=fopen(filename,"wb");
	if(fpBMP == 0)
		return 0;

	/* Write header */
	/* All values are in big endian order (LSB first) */

	// BMP signature + filesize
	fprintf(fpBMP,"%c%c%c%c%c%c%c%c%c%c", 66, 77, ucaBitmapSize[0],
			ucaBitmapSize[1], ucaBitmapSize[2], ucaBitmapSize[3], 0, 0,
			0, 0);

	// Image offset, infoheader size, image width
	fprintf(fpBMP,"%c%c%c%c%c%c%c%c%c%c", 54, 0, 0, 0, 40, 0 , 0, 0,
			(x_size & 0x00FF), (x_size & 0xFF00)>>8);

	// Image height, number of panels, num bits per pixel
	fprintf(fpBMP,"%c%c%c%c%c%c%c%c%c%c", 0, 0, (y_size & 0x00FF),
			(y_size & 0xFF00) >> 8, 0, 0, 1, 0, 24, 0);

	// Compression type 0, Size of image in bytes 0 because uncompressed
	fprintf(fpBMP,"%c%c%c%c%c%c%c%c%c%c", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	fprintf(fpBMP,"%c%c%c%c%c%c%c%c%c%c", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	fprintf(fpBMP,"%c%c%c%c", 0, 0 ,0, 0);

	for(i = y_size - 1; i >= 0; i--) {
		/* in bitmaps the bottom line of the image is at the
		   beginning of the file */
		for(j = 0; j < x_size; j++){
			putc((bitmapImage[i * x_size + j].B), fpBMP);
			putc((bitmapImage[i * x_size + j].G), fpBMP);
			putc((bitmapImage[i * x_size + j].R), fpBMP);
		}
		for(j = 0; j < x_size % 4; j++)
			putc(0, fpBMP);
	}

	fclose(fpBMP);
	return 1;
}

int LoadBitmapFile(char *filename, pixel_t* bitmapImage, int x_size, int y_size) {

  FILE *filePtr; //our file pointer
  int i,j;

  //open filename in read binary mode
  filePtr = fopen(filename,"rb");
  if (filePtr == NULL)
    return 0;

  //move file point to the begging of bitmap data
  fseek(filePtr, 54, SEEK_SET);


  for(i = y_size - 1; i >= 0; i--) {
    for(j = 0; j < x_size; j++){
      bitmapImage[i * x_size + j].B = (unsigned char) getc(filePtr);
      bitmapImage[i * x_size + j].G = (unsigned char) getc(filePtr);
      bitmapImage[i * x_size + j].R = (unsigned char) getc(filePtr);
    }
  }

  //close file and return bitmap image data
  fclose(filePtr);
  return 1;
}
